/**
 * 路由实现
 * Copyright(c) purenode
 * @author yangjian102621@gmail.com
 * MIT Licensed
 */

"use strict";

var url = require("url");
var configs = require("../configs.js");
var Request = require("./request.js");
var Response = require("./response.js");

/**
 * @param req http请求对象 
 * @param res http响应对象
 */
function Router(req, res, app) {
	
	var urlInfo = url.parse(req.url);
	var pathname = urlInfo.pathname;
	var controllerFile = null; //控制器名称

	if ( pathname != "/" ) {

		pathname = F_trim(pathname, '/');
		var pathInfo = pathname.split("/");
		if ( pathInfo.length != 3 ) {
		
			app.page404(res);
			return;
		
		} else { //查找控制器

			controllerFile = app.getConfig("controller_path")+pathInfo[0]+"/action/"+F_ucfirst(pathInfo[1])+"Action.js";
			app.setModule(pathInfo[0]);
			app.setAction(pathInfo[1]);
			if ( pathInfo[2] ) {
				app.setMethod(pathInfo[2]);
			} else {
				app.setMethod("index");
			}
		}

	} else { //访问默认页面
		
		var defaultPage = app.getConfig("default_page");
		controllerFile = app.getConfig("controller_path")+defaultPage[0]+"/action/"+F_ucfirst(defaultPage[1])+"Action.js";
		
		app.setModule(defaultPage[0]);
		app.setAction(defaultPage[1]);
		app.setMethod(defaultPage[2]);

	}

	var postData = "";
	req.addListener("data", function(postDataChunk) {
		postData += postDataChunk;
	});

	req.addListener("end", function() {
		app.config("POST_DATA", postData);
		var request = new Request(req, app);
		var response = new Response(res, app);
		var controller = require(controllerFile);
		res.writeHead(200, {"Content-Type" : "text/html; charset=UTF-8"});
		controller[app.getMethod()](request, response);
	});

	return;
}

exports.Router = Router;
